<template>
    <div class="examination-questions" ref="vantaRef">
        <div class="question-container">
            <div class="question-header">
                <h2 class="title">题目详情</h2>
            </div>
            <div class="question-content" v-loading="loading">
                <div v-if="currentExercise" class="exercise-detail">
                    <div class="info-item">
                        <span class="label">所属知识点：</span>
                        <div class="value tags">
                            <span class="tag knowledge-tag">
                                {{ currentExercise.graphNodeName }}
                            </span>
                        </div>
                    </div>
                    <div class="info-item">
                        <span class="label">题目内容：</span>
                        <div class="value question-text" v-html="currentExercise.questionBody"></div>
                    </div>

                    <div class="options-container">
                        <!-- 单选题 -->
                        <template v-if="currentExercise.questionType === '0'">
                            <div v-for="(option, index) in currentExercise.options" 
                                 :key="index"
                                 :class="['option-item', {
                                    'selected': userAnswers[currentIndex] === index,
                                    'correct': isSubmitted && index === currentExercise.correctAnswer,
                                    'wrong': isSubmitted && userAnswers[currentIndex] === index && index !== currentExercise.correctAnswer
                                 }]"
                                 @click="selectOption(index)">
                                <span class="option-label">{{ ['A', 'B', 'C', 'D'][index] }}</span>
                                <span class="option-content">{{ option }}</span>
                            </div>
                        </template>

                        <!-- 多选题 -->
                        <template v-if="currentExercise.questionType === '1'">
                            <div v-for="(option, index) in currentExercise.options" 
                                 :key="index"
                                 :class="['option-item', {
                                    'selected': userAnswers[currentIndex] && userAnswers[currentIndex].includes(index),
                                    'correct': isSubmitted && currentExercise.correctAnswer.includes(index),
                                    'wrong': isSubmitted && userAnswers[currentIndex] && userAnswers[currentIndex].includes(index) && !currentExercise.correctAnswer.includes(index)
                                 }]"
                                 @click="selectMultiOption(index)">
                                <span class="option-label">{{ ['A', 'B', 'C', 'D'][index] }}</span>
                                <span class="option-content">{{ option }}</span>
                            </div>
                        </template>

                        <!-- 判断题 -->
                        <template v-if="currentExercise.questionType === '2'">
                            <div class="judge-options">
                                <div :class="['judge-option', {
                                    'selected': userAnswers[currentIndex] === true,
                                    'correct': isSubmitted && currentExercise.correctAnswer === true,
                                    'wrong': isSubmitted && userAnswers[currentIndex] === true && currentExercise.correctAnswer !== true
                                }]"
                                @click="selectJudgeOption(true)">
                                    正确
                                </div>
                                <div :class="['judge-option', {
                                    'selected': userAnswers[currentIndex] === false,
                                    'correct': isSubmitted && currentExercise.correctAnswer === false,
                                    'wrong': isSubmitted && userAnswers[currentIndex] === false && currentExercise.correctAnswer !== false
                                }]"
                                @click="selectJudgeOption(false)">
                                    错误
                                </div>
                            </div>
                        </template>

                        <!-- 填空题和简答题 -->
                        <template v-if="currentExercise.questionType === '3' || currentExercise.questionType === '4'">
                            <vue-ueditor-wrap v-model="content"
                                editor-id="editor"
                                :config="editorConfig"
                                :editorDependencies="['ueditor.config.js','ueditor.all.js']"
                                @input="handleContentChange"
                            />
                        </template>
                    </div>

                    <div class="info-item mgt10" v-if="currentExercise.questionCategory == 0">
                        <span class="label">习题答案：</span>
                        <div class="value question-text" v-html="currentExercise.questionAnswer"></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 答题卡 -->
        <div class="answer-card">
            <div class="card-header">答题卡</div>
            <div class="card-content">
                <div v-for="(exercise, index) in questionList" 
                     :key="index"
                     :class="['question-number', {
                        'answered': isQuestionAnswered(index),
                        'current': currentIndex === index,
                        'correct': isSubmitted && isAnswerCorrect(index),
                        'wrong': isSubmitted && !isAnswerCorrect(index) && isQuestionAnswered(index),
                        'unanswered': hasVisited[index] && !isQuestionAnswered(index) && currentIndex !== index
                     }]"
                     @click="goToQuestion(index)">
                    {{ index + 1 }}
                </div>
            </div>
        </div>
        <!-- 操作按钮和导航按钮 -->
        <div class="navigation-buttons">
            <el-button type="primary" 
                       @click="prevQuestion" 
                       :disabled="currentIndex === 0">
                上一题
            </el-button>
            <el-button type="primary" 
                       @click="nextQuestion" 
                       :disabled="currentIndex === questionList.length - 1">
                下一题
            </el-button>
            <el-button v-if="!isSubmitted"
                      type="primary" 
                      icon="el-icon-check"
                      @click="submitExam">
                提交答题
            </el-button>
            <el-button type="danger" 
                      icon="el-icon-close" 
                      @click="exitExam">
                退出答题
            </el-button>
        </div>
    </div>
</template>

<script>
import { listQuestion, getQuestion, delQuestion, addQuestion, updateQuestion, randomQuestion, nodeQuestion, submitAnswer } from "@/api/question";
import { getInfo } from "@/api/login";
import * as THREE from "three";
import NET from "vanta/src/vanta.net";
import VueUeditorWrap from 'vue-ueditor-wrap'

export default {
    name: 'ExaminationQuestions',
    components: {
        VueUeditorWrap
    },
    data() {
        return {
            loading: true,
            currentExercise: null,
            currentIndex: 0,
            isSubmitted: false,
            userAnswers: [],
            questionList: [], // 存储接口获取的题目列表
            content: '<p>解：</p>',
            editorConfig: {
                serverUrl: 'http://192.168.3.119:8080',
                UEDITOR_HOME_URL: '/static/UEditorPlus/',
                UEDITOR_CORS_URL: '/static/UEditorPlus/',
                toolbars: [[
                    "fullscreen",
                    "undo",
                    "redo",
                    "formula",
                    "superscript",
                    "subscript",
                    "removeformat",
                    "forecolor",
                    "backcolor",
                    "fontfamily",
                    "fontsize",
                    "bold",
                    "justifyleft",
                    "justifycenter",
                    "justifyright",
                    "justifyjustify",
                    "|",
                    "simpleupload",
                    "insertimage",
                    "attachment",
                    "spechars",
                    "preview",
                ]],
                toolbarShows:{
                    "ai": false,
                },
                shortcutMenuShows: {
                    "ai": false,
                }, 
                minFrameHeight: 220,
                initialFrameHeight:220
            },
            // 存储每道题的作答内容
            answerContents: {},
            hasVisited: [], // 新增，记录每道题是否访问过
            userId: null // 用户ID
        };
    },
    computed: {
        isAllAnswered() {
            return this.questionList.every((_, index) => this.isQuestionAnswered(index));
        }
    },
    created() {
        // 获取用户信息
        getInfo().then(res => {
            if (res && res.user) {
                this.userId = res.user.userId;
            }
        }).catch(err => {
            console.error('获取用户信息失败:', err);
        });

        const nodeId = this.$route.query.nodeId;
        if (nodeId) {
            // 专项训练，按节点获取题目
            nodeQuestion({ nodeId, limit: 10 }).then(res => {
                this.questionList = res.data || [];
                this.userAnswers = new Array(this.questionList.length).fill(null);
                if (this.questionList.length > 0) {
                    this.currentExercise = this.questionList[0];
                }
                this.loading = false;
            }).catch(err => {
                console.error('获取专项训练题目失败:', err);
                this.loading = false;
            });
        } else {
            // 极速训练，原有逻辑
            this.getList();
        }
        this.hasVisited = [];
    },
    mounted() {
        this.vantaEffect = NET({
            el: this.$refs.vantaRef,
            THREE: THREE,
            mouseControls: true,
            touchControls: true,
            gyroControls: false,
            minHeight: 200.00,
            minWidth: 200.00,
            scale: 1.00,
            scaleMobile: 1.00,
            color: 0x4db9cc,
            backgroundColor: 0x25163d,
            points: 11.00,
            spacing: 16.00
        });
    },
    watch: {
        currentIndex(newVal) {
            this.$set(this.hasVisited, newVal, true);
        }
    },
    methods: {
        // 获取题目列表
        getList() {
            const queryParams = {
                count:10
            }
            randomQuestion(queryParams).then(res => {
                console.log('题目数据', res);
                this.questionList = res.data || [];
                // 初始化答案数组
                this.userAnswers = new Array(this.questionList.length).fill(null);
                // 设置当前题目
                if (this.questionList.length > 0) {
                    this.currentExercise = this.questionList[0];
                }
                this.loading = false;
            }).catch(err => {
                console.error('获取题目失败:', err);
                this.loading = false;
            });
        },
        selectOption(index) {
            if (!this.isSubmitted) {
                this.$set(this.userAnswers, this.currentIndex, index);
            }
        },
        selectMultiOption(index) {
            if (!this.isSubmitted) {
                if (!this.userAnswers[this.currentIndex]) {
                    this.$set(this.userAnswers, this.currentIndex, []);
                }
                const currentAnswers = [...this.userAnswers[this.currentIndex]];
                const optionIndex = currentAnswers.indexOf(index);
                
                if (optionIndex === -1) {
                    currentAnswers.push(index);
                } else {
                    currentAnswers.splice(optionIndex, 1);
                }
                this.$set(this.userAnswers, this.currentIndex, currentAnswers);
            }
        },
        selectJudgeOption(value) {
            if (!this.isSubmitted) {
                this.$set(this.userAnswers, this.currentIndex, value);
            }
        },
        handleContentChange(content) {
            this.answerContents[this.currentIndex] = content;
        },
        prevQuestion() {
            if (this.currentIndex > 0) {
                this.currentIndex--;
                this.currentExercise = this.questionList[this.currentIndex];
                if (this.currentExercise.questionType === '3' || this.currentExercise.questionType === '4') {
                    this.content = this.answerContents[this.currentIndex] || '<p>解：</p>';
                } else {
                    this.content = '';
                }
                this.$set(this.hasVisited, this.currentIndex, true);
            }
        },
        nextQuestion() {
            if (this.currentIndex < this.questionList.length - 1) {
                this.currentIndex++;
                this.currentExercise = this.questionList[this.currentIndex];
                if (this.currentExercise.questionType === '3' || this.currentExercise.questionType === '4') {
                    this.content = this.answerContents[this.currentIndex] || '<p>解：</p>';
                } else {
                    this.content = '';
                }
                this.$set(this.hasVisited, this.currentIndex, true);
            }
        },
        goToQuestion(index) {
            this.currentIndex = index;
            this.currentExercise = this.questionList[index];
            if (this.currentExercise.questionType === '3' || this.currentExercise.questionType === '4') {
                this.content = this.answerContents[this.currentIndex] || '<p>解：</p>';
            } else {
                this.content = '';
            }
            this.$set(this.hasVisited, index, true);
        },
        async submitExam() {
            if (!this.isAllAnswered) {
                const confirm = await this.$confirm('有未作答的题目，确认提交吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(() => false);
                
                if (!confirm) return;
            }

            // 检查是否有用户ID
            if (!this.userId) {
                // 如果用户ID不存在，尝试重新获取
                try {
                    const res = await getInfo();
                    if (res && res.user) {
                        this.userId = res.user.userId;
                    } else {
                        this.$message.error('无法获取用户信息，请重新登录');
                        return;
                    }
                } catch (error) {
                    this.$message.error('获取用户信息失败，请重新登录');
                    console.error('获取用户信息失败:', error);
                    return;
                }
            }

            // 构建提交数据
            const submitData = this.questionList.map((question) => ({
                userId: this.userId,
                answerBody: this.formatAnswerForSubmit(question),
                answerScore: '',
                nodeId: question.nodeId || question.graphNodeId || '' // 确保获取正确的nodeId字段
            }));

            console.log('提交的答案数据:', submitData);

            try {
                await submitAnswer(submitData);
                this.isSubmitted = true;
                this.$message.success('提交成功');
            } catch (error) {
                this.$message.error('提交失败');
                console.error('提交答案失败:', error);
            }
        },
        
        // 格式化答案内容用于提交
        formatAnswerForSubmit(question) {
            const index = this.questionList.indexOf(question);
            if (index === -1) return '';
            
            switch (question.questionType) {
                case '0': // 单选题
                    return this.userAnswers[index] !== null ? String(this.userAnswers[index]) : '';
                case '1': // 多选题
                    if (!this.userAnswers[index] || this.userAnswers[index].length === 0) return '';
                    // 多选题返回格式化的数组字符串
                    return JSON.stringify(this.userAnswers[index].sort());
                case '2': // 判断题
                    // 判断题返回布尔值的字符串表示
                    return this.userAnswers[index] !== null ? (this.userAnswers[index] ? 'true' : 'false') : '';
                case '3': // 填空题
                case '4': // 简答题
                    return this.answerContents[index] || '';
                default:
                    return '';
            }
        },
        exitExam() {
            window.close();
        },
        // 判断题目是否已作答
        isQuestionAnswered(index) {
            const question = this.questionList[index];
            if (!question) return false;

            switch (question.questionType) {
                case '0': // 单选题
                    return this.userAnswers[index] !== null;
                case '1': // 多选题
                    return this.userAnswers[index] && this.userAnswers[index].length > 0;
                case '2': // 判断题
                    return this.userAnswers[index] !== null;
                case '3': // 填空题
                case '4': // 简答题
                    return this.answerContents[index] && this.answerContents[index].trim() !== '<p>解：</p>';
                default:
                    return false;
            }
        },
        // 判断答案是否正确
        isAnswerCorrect(index) {
            const question = this.questionList[index];
            if (!question) return false;

            switch (question.questionType) {
                case '0': // 单选题
                    return this.userAnswers[index] === question.correctAnswer;
                case '1': // 多选题
                    return JSON.stringify(this.userAnswers[index]) === JSON.stringify(question.correctAnswer);
                case '2': // 判断题
                    return this.userAnswers[index] === question.correctAnswer;
                case '3': // 填空题
                case '4': // 简答题
                    return true; // 主观题不判断正确性
                default:
                    return false;
            }
        }
    }
};
</script>

<style lang="scss" scoped>
.examination-questions {
    width: 100%;
        height: 100vh;
    background: #f5f6fb;
    display: flex;
    justify-content: flex-end;
    box-sizing: border-box;
    padding: 20px;
    position: relative;
}

.question-container {
    width: 100%;
    max-width: 1400px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    overflow-y: auto;
    margin-right: 200px;
}

.navigation-buttons {
    position: fixed;
    right: 40px;
    bottom: 40px;
    display: flex;
    flex-direction: column;
    gap: 16px;
    width: 120px;

    .el-button {
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 12px 15px;
        margin-left: 0 !important;

        & + .el-button {
            margin-left: 0;
        }

        &.el-button--warning {
            background-color: #e6a23c;
            border-color: #e6a23c;
            color: #fff;
            
            &:hover, &:focus {
                background-color: #ebb563;
                border-color: #ebb563;
                color: #fff;
            }
        }
    }
}

.options-container {
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    gap: 12px;
}

.option-item {
    display: flex;
    align-items: center;
    padding: 12px 16px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
        background-color: #f5f7fa;
        border-color: #409eff;
    }

    &.selected {
        background-color: #ecf5ff;
        border-color: #409eff;
    }

    &.correct {
        background-color: #f0f9eb;
        border-color: #67c23a;
    }

    &.wrong {
        background-color: #fef0f0;
        border-color: #f56c6c;
    }

    .option-label {
        font-weight: bold;
        margin-right: 12px;
        color: #409eff;
    }

    .option-content {
        color: #606266;
    }
}

.submit-btn-container {
    margin-top: 24px;
    display: flex;
    justify-content: space-between;
    gap: 16px;
}

.question-header {
    padding: 16px 20px;
    border-bottom: 1px solid #eee;

    .title {
        margin: 0;
        font-size: 18px;
        font-weight: bold;
        color: #000000;
    }
}

.question-content {
    padding: 20px;
    min-height: 400px;
}

.exercise-detail {
    .info-item {
        margin-bottom: 20px;

        .label {
            display: block;
            font-weight: 500;
            color: #000000;
            margin-bottom: 8px;
        }

        .value {
            color: #000000;

            &.description {
                padding: 12px;
                background: #f5f5f5;
                border-radius: 4px;
                line-height: 1.6;
            }

            &.question-text, &.answer-text {
                padding: 12px;
                background: #f5f5f5;
                border-radius: 4px;
                line-height: 1.6;
                white-space: pre-line;
            }

            &.tags {
                display: flex;
                flex-wrap: wrap;
                gap: 8px;
                cursor: pointer;
                .tag {
                    padding: 4px 8px;
                    border-radius: 4px;
                    font-size: 12px;
                    color: #fff;

                    &.knowledge-tag {
                        background: #2196F3;
                    }

                    &.prerequisite-tag {
                        background: #4CAF50;
                    }

                    &.similar-tag {
                        background: #FF9800;
                    }
                }
            }
        }
    }
}

.answer-card {
    position: fixed;
    left: 40px;
    top: 20px;
    width: 200px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
    padding: 16px;

    .card-header {
        font-size: 16px;
        font-weight: bold;
        color: #000000;
        margin-bottom: 16px;
        padding-bottom: 8px;
        border-bottom: 1px solid #eee;
        text-align: center;
    }

    .card-content {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        justify-content: center;

        .question-number {
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            color: #606266;
            transition: all 0.3s;

            &:hover {
                border-color: #409eff;
                color: #409eff;
            }

            &.answered {
                background: #ecf5ff;
                border-color: #409eff;
                color: #409eff;
            }

            &.current {
                background: #409eff;
                border-color: #409eff;
                color: #fff;
            }

            &.correct {
                background: #67c23a;
                border-color: #67c23a;
                color: #fff;
            }

            &.wrong {
                background: #f56c6c;
                border-color: #f56c6c;
                color: #fff;
            }

            &.unanswered {
                background: #f2f2f2 !important;
                border-color: #e0e0e0 !important;
                color: #bdbdbd !important;
            }
        }
    }
}
.mgt10{
    margin-top: 20px;
}

.judge-options {
    display: flex;
    gap: 20px;
    margin-top: 20px;
}

.judge-option {
    flex: 1;
    padding: 15px;
    text-align: center;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 16px;

    &:hover {
        background-color: #f5f7fa;
        border-color: #409eff;
    }

    &.selected {
        background-color: #ecf5ff;
        border-color: #409eff;
    }

    &.correct {
        background-color: #f0f9eb;
        border-color: #67c23a;
    }

    &.wrong {
        background-color: #fef0f0;
        border-color: #f56c6c;
    }
}
</style>

